package com.hjh.gameforum.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hjh.gameforum.dto.TopicDto;
import com.hjh.gameforum.dto.TopicQueryParem;
import com.hjh.gameforum.dto.UserHomeQueryParem;
import com.hjh.gameforum.entity.Topic;
import com.hjh.gameforum.enums.TopicStatus;
import com.hjh.gameforum.mapper.FavoritesMapper;
import com.hjh.gameforum.mapper.TopicMapper;
import com.hjh.gameforum.mapper.UserProfileMapper;
import com.hjh.gameforum.result.PageResult;
import com.hjh.gameforum.service.TopicService;
import com.hjh.gameforum.utils.CurrentHolder;
import com.hjh.gameforum.vo.TopicVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.TextStyle;
import java.util.*;

@Service
@Slf4j
public class TopicServiceImpi implements TopicService {
    @Autowired
    private TopicMapper topicMapper;

    @Autowired
    private FavoritesMapper favoritesMapper;

    @Autowired
    private UserProfileMapper userProfileMapper;

    @Override
    public PageResult<TopicVo> getTopics(TopicQueryParem topicQueryParem) {
        PageHelper.startPage(topicQueryParem.getPage(), topicQueryParem.getPageSize());
        List<TopicVo> topics = topicMapper.getTopics(topicQueryParem.getCategoryId(), topicQueryParem.getTitle());
        Page<TopicVo> page = (Page<TopicVo>) topics;
        return new PageResult<>(page.getTotal(), page.getResult());
    }

    @Override
    @Transactional
    public void createTopic(TopicDto topicDto) {
        Long userId =CurrentHolder.getCurrentId();
        Topic topic = Topic.builder()
                .title(topicDto.getTitle())
                .content(topicDto.getContent())
                .userId(userId)
                .categoryId(topicDto.getCategoryId())
                .viewCount(1)
                .status(TopicStatus.open)
                .createdAt(LocalDateTime.now())
                .updatedAt(LocalDateTime.now())
                .imageUrl(topicDto.getImageUrl())
                .build();
        log.info("创建话题: {}", topic);
        topicMapper.createTopic(topic);
        userProfileMapper.increaseTopics(userId);
    }

    @Override
    public List<TopicVo> getHotTopics() {
        List<TopicVo> topics = topicMapper.getHotTopics();
        return topics;
    }

    @Override
    public TopicVo getTopicById(Integer id) {
        return topicMapper.getTopicById(id);
    }

    @Override
    public void updateTopicViews(Integer id) {
        topicMapper.updateTopicViews(id);
    }
    @Override
    @Transactional
    public void likeTopic(Integer topicId, Integer AuthorId) {
        Long userId =CurrentHolder.getCurrentId();
        favoritesMapper.createFavorites(userId, topicId);
        topicMapper.likeTopic(topicId);
        userProfileMapper.increaseLikes(AuthorId);
    }

    @Override
    @Transactional
    public void unlikeTopic(Integer topicId,Integer AuthorId) {
        Long userId =CurrentHolder.getCurrentId();
        favoritesMapper.deleteFavorites(userId, topicId);
        topicMapper.unlikeTopic(topicId);
        userProfileMapper.reduceLikes(AuthorId);
    }

    @Override
    public boolean getLikeStatus(Integer id) {
        Long userId =CurrentHolder.getCurrentId();
        if (favoritesMapper.getFavorites(userId, id)){
            return true;
        }
        return false;
    }

    @Override
    public List<TopicVo> getPinnedTopics() {
        List<TopicVo> topicVoList = topicMapper.getPinnedTopics();
        return topicVoList;
    }

    @Override
    public void updateTopic( TopicDto topicDto) {
        Topic topic = Topic.builder()
                .topicId(topicDto.getTopicId())
                .title(topicDto.getTitle())
                .content(topicDto.getContent())
                .categoryId(topicDto.getCategoryId())
                .updatedAt(LocalDateTime.now())
                .imageUrl(topicDto.getImageUrl())
                .build();
        topicMapper.updateTopic(topic);

    }

    @Override
    public void setTopicStatus(Long topicId, Integer statusId) {
        Topic topic = Topic.builder()
                .topicId(topicId)
                .updatedAt(LocalDateTime.now())
                .build();
        if (statusId == 1)
            topic.setStatus(TopicStatus.open);
        else if (statusId == 2)
            topic.setStatus(TopicStatus.closed);
        else if (statusId == 3)
            topic.setStatus(TopicStatus.pinned);
        else if (statusId == 4)
            topic.setStatus(TopicStatus.hidden);
        else
            throw new IllegalArgumentException("Invalid status ID: " + statusId);

        topicMapper.updateTopic(topic);

    }

    @Override
    @Transactional
    public void deleteTopic(Long topicId) {
        topicMapper.deleteTopic(topicId);
        userProfileMapper.reduceTopics(CurrentHolder.getCurrentId());
        favoritesMapper.deleteFavoritesByTopicId(topicId);

    }

    @Override
    public List<TopicVo> getTopicTop(String unit) {
        if(unit.equals("views")){
            return topicMapper.getHotTopics();
        } else if (unit.equals("likes")) {
            return topicMapper.getLikeTop();
        } else {
            throw new IllegalArgumentException("Invalid unit: " + unit);
        }
    }

    @Override
    public Map<String, Object> getTopicCountStats(String unit) {
        Map<String, Object> result = new HashMap<>();
        List<String> x = new ArrayList<>();
        List<Integer> y = new ArrayList<>();
        if ("day".equals(unit)) {
            for (int i = 6; i >= 0; i--) {
                LocalDate date = LocalDate.now().minusDays(i);
                x.add(date.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.CHINA)); // 周几
                int count = topicMapper.getTopicCountByDate(date);
                y.add(count);
            }
        }
        else if ("week".equals(unit)) {
            // 最近4周
            for (int i = 3; i >= 0; i--) {
                LocalDate monday = LocalDate.now().minusWeeks(i).with(DayOfWeek.MONDAY);
                LocalDate sunday = monday.plusDays(6);
                x.add("第" + (4 - i) + "周");
                int count = topicMapper.getTopicCountByDateRange(monday, sunday);
                y.add(count);
            }
        }
        else if ("month".equals(unit)) {
            // 最近12个月
            for (int i = 11; i >= 0; i--) {
                YearMonth ym = YearMonth.now().minusMonths(i);
                x.add(ym.getMonthValue() + "月");
                int count = topicMapper.getTopicCountByMonth(ym.getYear(), ym.getMonthValue());
                y.add(count);
            }
        }
        result.put("x", x);
        result.put("y", y);
        return result;
    }

    @Override
    public Long getTotalTopics() {
        return topicMapper.getTotalTopics();
    }

    @Override
    public PageResult<TopicVo> getUserHomeTopics(UserHomeQueryParem userHomeQueryParem) {
        PageHelper.startPage(userHomeQueryParem.getPage(), userHomeQueryParem.getPageSize());
        List<TopicVo> topics = topicMapper.getUserHomeTopics(userHomeQueryParem.getUserId());
        Page<TopicVo> page = (Page<TopicVo>) topics;
        return new PageResult<>(page.getTotal(), page.getResult());
    }


}
